#include "adminmanager.h"
#include <QCoreApplication>
#include <QMessageBox>
#include <QDebug>
#include <QDate>
#include <QVariantList>

AdminManager::AdminManager(SqlOperator *dbOperator, QObject *parent) : QObject(parent),
    m_dbOperator(dbOperator),
    m_ownsDbOperator(false)
{
    // 确保数据库连接已打开
    if (!m_dbOperator->isOpen()) {
        if (!initDatabase()) {
            emit operationResult(false, "数据库连接失败");
        }
    }
}

AdminManager::AdminManager(QObject *parent) : QObject(parent),
    m_dbOperator(new SqlOperator()),
    m_ownsDbOperator(true)
{
    initDatabase();
}

AdminManager::~AdminManager()
{
    if (m_dbOperator && m_ownsDbOperator)
    {
        m_dbOperator->close();
        delete m_dbOperator;
        m_dbOperator = nullptr;
    }
}

bool AdminManager::initDatabase()
{
    QString appDir = QCoreApplication::applicationDirPath();
    QString dbPath = appDir + "/../../sql/company.db";
    if (!m_dbOperator->open(dbPath, "adminManagerConnection"))
    {
        emit operationResult(false, "无法连接到数据库: " + m_dbOperator->lastError());
        return false;
    }
    return true;
}
//添加新员工
bool AdminManager::addEmployee(const QString &empId, const QString &empName, const QString &gender,
                              const QString &position, int deptId, const QString &username,
                              const QString &password)
{
    // 验证输入
    if (empId.isEmpty() || empName.isEmpty() || username.isEmpty() || password.isEmpty())
    {
        emit operationResult(false, "员工ID、姓名、用户名和密码不能为空");
        return false;
    }

    // 检查员工ID是否已存在
    QList<QString> fields = {"emp_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("emp_id", empId);
    QList<QVariantList> data;
    if (m_dbOperator->selectData("employee", fields, whereConditions, data))
    {
        if (!data.isEmpty())
        {
            emit operationResult(false, "员工ID已存在");
            return false;
        }
    }
    else
    {
        emit operationResult(false, "检查员工ID失败: " + m_dbOperator->lastError());
        return false;
    }

    // 检查用户名是否已存在
    whereConditions.clear();
    whereConditions.insert("username", username);
    if (m_dbOperator->selectData("login", fields, whereConditions, data))
    {
        if (!data.isEmpty())
        {
            emit operationResult(false, "用户名已存在");
            return false;
        }
    }
    else
    {
        emit operationResult(false, "检查用户名失败: " + m_dbOperator->lastError());
        return false;
    }

   // 开始事务
    if (!m_dbOperator->transaction())
    {
        emit operationResult(false, "开启事务失败: " + m_dbOperator->lastError());
        return false;
    }

    // 1. 插入员工基本信息
    QList<QString> employeeFields = {"emp_id", "emp_name", "gender", "position", "dept_id"};
    QVariantList employeeData;
    employeeData << empId << empName << gender << position << deptId;

    if (!m_dbOperator->insertRowData("employee", employeeFields, employeeData))
    {
        m_dbOperator->rollback();
        emit operationResult(false, "插入员工基本信息失败: " + m_dbOperator->lastError());
        return false;
    }

    // 2. 增加对应部门人数
    QString updateDeptSql = QString("UPDATE department SET dept_count = dept_count + 1 WHERE dept_id = %1").arg(deptId);
    if (!m_dbOperator->exec(updateDeptSql))
    {
        m_dbOperator->rollback();
        emit operationResult(false, "更新部门人数失败: " + m_dbOperator->lastError());
        return false;
    }

    // 3. 创建员工登录账号
    QList<QString> loginFields = {"username", "emp_id", "password"};
    QVariantList loginData;
    loginData << username << empId << password;

    if (!m_dbOperator->insertRowData("login", loginFields, loginData))
    {
        m_dbOperator->rollback();
        emit operationResult(false, "创建员工登录账号失败: " + m_dbOperator->lastError());
        return false;
    }

    // 提交事务
   if (!m_dbOperator->commit())
    {
        m_dbOperator->rollback();
        emit operationResult(false, "提交事务失败: " + m_dbOperator->lastError());
        return false;
    }

    emit operationResult(true, "员工添加成功");
    return true;
}
//员工离职
bool AdminManager::removeEmployee(const QString &empId)
{
    // 验证输入
    if (empId.isEmpty())
    {
        emit operationResult(false, "员工ID不能为空");
        return false;
    }

    // 数据库连接已在构造函数中确保打开

    // 检查员工是否存在
    QList<QString> fields = {"emp_id", "dept_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("emp_id", empId);
    QList<QVariantList> data;
    if (m_dbOperator->selectData("employee", fields, whereConditions, data))
    {
        if (data.isEmpty())
        {
            emit operationResult(false, "未找到该员工");
            return false;
        }
    }
    else
    {
        emit operationResult(false, "检查员工信息失败: " + m_dbOperator->lastError());
        return false;
    }

    // 获取员工所在部门ID
    int deptId = data[0][1].toInt();

    // 开始事务
    if (!m_dbOperator->transaction())
    {
        emit operationResult(false, "开启事务失败: " + m_dbOperator->lastError());
        return false;
    }

    // 1. 删除登录信息
    if (!m_dbOperator->deleteData("login", whereConditions))
    {
        m_dbOperator->rollback();
        emit operationResult(false, "删除登录信息失败: " + m_dbOperator->lastError());
        return false;
    }

    // 2. 更新部门人数
    QString updateDeptSql = QString("UPDATE department SET dept_count = dept_count - 1 WHERE dept_id = %1").arg(deptId);
    if (!m_dbOperator->exec(updateDeptSql))
    {
        m_dbOperator->rollback();
        emit operationResult(false, "更新部门人数失败: " + m_dbOperator->lastError());
        return false;
    }

    // 3. 删除员工信息
    if (!m_dbOperator->deleteData("employee", whereConditions))
    {
        m_dbOperator->rollback();
        emit operationResult(false, "删除员工信息失败: " + m_dbOperator->lastError());
        return false;
    }

    // 提交事务
    if (!m_dbOperator->commit())
    {
        m_dbOperator->rollback();
        emit operationResult(false, "提交事务失败: " + m_dbOperator->lastError());
        return false;
    }

    emit operationResult(true, "员工离职处理成功");
    return true;
}
//工资查询
QList<QVariantList> AdminManager::getSalaryDetailsByDate(const QString &startDate, const QString &endDate)
{
    QList<QVariantList> results;

    // 数据库连接已在构造函数中确保打开

    // 验证日期格式 (假设格式为"YYYY-MM-DD")
    QRegExp dateReg("^(19|20)\\d\\d-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$");
    if (!dateReg.exactMatch(startDate) || !dateReg.exactMatch(endDate))
    {
        emit operationResult(false, "日期格式不正确，请使用YYYY-MM-DD格式");
        return results;
    }

    // 构建SQL查询语句
    QString sql = "SELECT e.emp_id, e.emp_name, e.position, d.dept_name, s.basic_salary, s.deduction, s.actual_salary, s.payment_date "
                  "FROM salary s JOIN employee e ON s.emp_id = e.emp_id "
                  "JOIN department d ON e.dept_id = d.dept_id "
                  "WHERE s.payment_date BETWEEN '" + startDate + "' AND '" + endDate + "'";

    // 定义要查询的字段
    QList<QString> fields;
    fields << "emp_id" << "emp_name" << "position" << "dept_name" << "basic_salary" << "deduction" << "actual_salary" << "payment_date";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success)
    {
        emit operationResult(false, QString("查询失败: %1").arg(m_dbOperator->lastError()));
    }
    else if (results.isEmpty())
    {
        emit operationResult(false, "未找到该日期范围内的工资数据");
    }
    else
    {
        emit operationResult(true, "查询成功");
    }

    return results;
}
// 根据月份和部门查询工资详情
QList<QVariantList> AdminManager::getSalaryDetailsByMonthAndDept(const QString &month, int deptId)
{
    QList<QVariantList> results;

    // 数据库连接已在构造函数中确保打开

    // 构建SQL查询语句
    QString sql = "SELECT e.emp_id, e.emp_name, e.position, d.dept_name, s.basic_salary, s.deduction, s.actual_salary, s.payment_date "
                  "FROM salary s JOIN employee e ON s.emp_id = e.emp_id "
                  "JOIN department d ON e.dept_id = d.dept_id ";

    bool hasCondition = false;

    // 如果月份不为空，则验证格式并添加条件
    if (!month.isEmpty())
    {
        // 验证月份格式 (YYYY-MM)
        QRegExp dateReg("^(19|20)\\d\\d-(0[1-9]|1[0-2])$");
        if (!dateReg.exactMatch(month))
        {
            emit operationResult(false, "月份格式不正确，请使用YYYY-MM格式");
            return results;
        }

        sql += "WHERE substr(s.payment_period, 1, 7) = '" + month + "'";
        hasCondition = true;
    }

    // 如果选择了特定部门
    if (deptId != -1)
    {
        if (hasCondition)
        {
            sql += " AND e.dept_id = " + QString::number(deptId);
        }
        else
        {
            sql += "WHERE e.dept_id = " + QString::number(deptId);
            hasCondition = true;
        }
    }

    // 定义要查询的字段
    QList<QString> fields;
    fields << "emp_id" << "emp_name" << "position" << "dept_name" << "basic_salary" << "deduction" << "actual_salary" << "payment_date";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success)
    {
        emit operationResult(false, QString("查询失败: %1").arg(m_dbOperator->lastError()));
    }
    else if (results.isEmpty())
    {
        emit operationResult(false, month.isEmpty() ? "未找到工资数据" : "未找到该月份的工资数据");
    }
    else
    {
        emit operationResult(true, "查询成功");
    }

    return results;
}
//员工打卡信息
QList<QVariantList> AdminManager::getEmployeeAttendance(const QString &empId, const QString &startDate, const QString &endDate)
{
    QList<QVariantList> results;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        emit operationResult(false, "数据库连接失败");
        return results;
    }

    // 构建SQL查询语句
    QString sql = "SELECT a.record_id, a.emp_id, e.emp_name, a.check_in_time, a.check_out_time, a.date, a.status "
                 "FROM attendance a JOIN employee e ON a.emp_id = e.emp_id "
                 "WHERE 1=1 ";

    if (!empId.isEmpty())
    {
        sql += " AND a.emp_id = '" + empId + "'";
    }

    if (!startDate.isEmpty())
    {
        sql += " AND a.date >= '" + startDate + "'";
    }

    if (!endDate.isEmpty())
    {
        sql += " AND a.date <= '" + endDate + "'";
    }

    sql += " ORDER BY a.date DESC, a.check_in_time DESC";

    // 定义要查询的字段
    QList<QString> fields;
    fields << "record_id" << "emp_id" << "emp_name" << "check_in_time" << "check_out_time" << "date" << "status";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success)
    {
        emit operationResult(false, QString("查询打卡记录失败: %1").arg(m_dbOperator->lastError()));
    }

    return results;
}
//查看员工信息
QList<QVariantList> AdminManager::searchEmployees(const QString &empId, const QString &empName, const QString &department)
{
    QList<QVariantList> results;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        emit operationResult(false, "数据库连接失败");
        return results;
    }

    // 构建SQL查询语句
    QString sql = "SELECT e.emp_id, e.emp_name, e.gender, e.position, d.dept_name FROM employee e JOIN department d ON e.dept_id = d.dept_id";

    bool hasCondition = false;
    if (!empId.isEmpty())
    {
        sql += " WHERE e.emp_id = '" + empId + "'";
        hasCondition = true;
    }

    if (!empName.isEmpty())
    {
        if (hasCondition)
        {
            sql += " AND";
        } else {
            sql += " WHERE";
            hasCondition = true;
        }
        sql += " e.emp_name LIKE '" + QString("%%1%").arg(empName).replace("'", "''") + "'";
    }

    if (!department.isEmpty())
    {
        if (hasCondition)
        {
            sql += " AND";
        } else {
            sql += " WHERE";
            hasCondition = true;
        }
        sql += " d.dept_name LIKE '" + QString("%%1%").arg(department).replace("'", "''") + "'";
    }

    // 定义要查询的字段
    QList<QString> fields;
    fields << "emp_id" << "emp_name" << "gender" << "position" << "dept_name";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success)
    {
        emit operationResult(false, QString("查询失败: %1").arg(m_dbOperator->lastError()));
    }

    return results;
}
// 查看待审核的调岗申请
QList<QVariantList> AdminManager::getPendingTransferRequests()
{
    QList<QVariantList> results;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        emit operationResult(false, "数据库连接失败");
        return results;
    }

    // 构建SQL查询语句
    QString sql = "SELECT tr.*, e.emp_name, d_old.dept_name AS old_dept_name, d_new.dept_name AS new_dept_name "
                 "FROM transfer_request tr "
                 "JOIN employee e ON tr.emp_id = e.emp_id "
                 "JOIN department d_old ON tr.old_dept_id = d_old.dept_id "
                 "JOIN department d_new ON tr.new_dept_id = d_new.dept_id "
                 "WHERE tr.status = '未审核' "
                 "ORDER BY tr.request_time";

    // 定义要查询的字段
    QList<QString> fields;
    fields << "request_id" << "emp_id" << "old_dept_id" << "new_dept_id" << "reason" << "request_time" << "status" << "emp_name" << "old_dept_name" << "new_dept_name";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success)
    {
        emit operationResult(false, QString("查询待审核调岗申请失败: %1").arg(m_dbOperator->lastError()));
    }

    return results;
}
//同意调岗申请
bool AdminManager::approveTransferRequest(const QString &requestId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        emit operationResult(false, "数据库连接失败");
        return false;
    }

    // 开始事务
    if (!m_dbOperator->transaction())
    {
        emit operationResult(false, "开启事务失败: " + m_dbOperator->lastError());
        return false;
    }

    try
    {
        // 1. 更新调岗申请状态
        QString updateRequestSql = QString("UPDATE transfer_request SET status = '同意' WHERE request_id = '%1'").arg(requestId);
        if (!m_dbOperator->exec(updateRequestSql))
        {
            throw QString("更新调岗申请状态失败: " + m_dbOperator->lastError());
        }

        // 2. 获取调岗相关信息
        QString getRequestSql = QString("SELECT emp_id, old_dept_id, new_dept_id FROM transfer_request WHERE request_id = '%1'").arg(requestId);
        QList<QString> fields = {"emp_id", "old_dept_id", "new_dept_id"};
        QList<QVariantList> requestData;
        if (!m_dbOperator->selectDataBySql(getRequestSql, fields, requestData) || requestData.isEmpty())
        {
            throw QString("获取调岗申请信息失败");
        }

        QString empId = requestData[0][0].toString();
        int oldDeptId = requestData[0][1].toInt();
        int newDeptId = requestData[0][2].toInt();

        // 3. 更新员工部门
        QString updateEmployeeSql = QString("UPDATE employee SET dept_id = %1 WHERE emp_id = '%2'").arg(newDeptId).arg(empId);
        if (!m_dbOperator->exec(updateEmployeeSql))
        {
            throw QString("更新员工部门失败: " + m_dbOperator->lastError());
        }

        // 4. 更新原部门人数
        QString updateOldDeptSql = QString("UPDATE department SET dept_count = dept_count - 1 WHERE dept_id = %1").arg(oldDeptId);
        if (!m_dbOperator->exec(updateOldDeptSql))
        {
            throw QString("更新原部门人数失败: " + m_dbOperator->lastError());
        }

        // 5. 更新新部门人数
        QString updateNewDeptSql = QString("UPDATE department SET dept_count = dept_count + 1 WHERE dept_id = %1").arg(newDeptId);
        if (!m_dbOperator->exec(updateNewDeptSql))
        {
            throw QString("更新新部门人数失败: " + m_dbOperator->lastError());
        }

        // 提交事务
        if (!m_dbOperator->commit())
        {
            throw QString("提交事务失败: " + m_dbOperator->lastError());
        }

        emit operationResult(true, "调岗申请已同意");
        return true;
    } catch (const QString &error) {
        m_dbOperator->rollback();
        emit operationResult(false, error);
        return false;
    }
}
//拒绝调岗申请
bool AdminManager::rejectTransferRequest(const QString &requestId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        emit operationResult(false, "数据库连接失败");
        return false;
    }

    // 更新调岗申请状态
    QString sql = QString("UPDATE transfer_request SET status = '不同意' WHERE request_id = '%1'").arg(requestId);
    if (!m_dbOperator->exec(sql))
    {
        emit operationResult(false, QString("拒绝调岗申请失败: %1").arg(m_dbOperator->lastError()));
        return false;
    }

    emit operationResult(true, "调岗申请已拒绝");
    return true;
}
// 查看待审核的请假申请
QList<QVariantList> AdminManager::getPendingLeaveRequests()
{
    QList<QVariantList> results;
    
    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return results;
    }
    
    // 检查leave_request表是否存在
    if (!m_dbOperator->isExistTable("leave_request")) {
        emit operationResult(false, "leave_request表不存在");
        return results;
    }
    
    // 查询待审核的请假申请
    QList<QString> fields = {"request_id", "emp_id", "leave_type", "start_date", "end_date", "reason", "request_time"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("status", "未审核");
    
    bool success = m_dbOperator->selectData("leave_request", fields, whereConditions, results);
    
    if (!success) {
        emit operationResult(false, "查询请假申请失败: " + m_dbOperator->lastError());
        return results;
    }
    
    return results;
}
// 按部门发放工资
bool AdminManager::distributeSalaryByDept(int deptId, const QString &paymentPeriod)
{
    // 验证输入
    if (deptId == -1 || paymentPeriod.isEmpty())
    {
        emit operationResult(false, "部门ID和发放周期不能为空");
        return false;
    }

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        emit operationResult(false, "数据库连接失败");
        return false;
    }

    // 开始事务
    if (!m_dbOperator->transaction())
    {
        emit operationResult(false, "开启事务失败: " + m_dbOperator->lastError());
        return false;
    }

    try
    {
        // 1. 获取部门名称
        QString deptName;
        QList<QString> deptFields = {"dept_name"};
        QHash<QString, QVariant> deptConditions;
        deptConditions.insert("dept_id", deptId);
        QList<QVariantList> deptData;
        if (!m_dbOperator->selectData("department", deptFields, deptConditions, deptData) || deptData.isEmpty())
        {
            throw QString("未找到部门信息");
        }
        deptName = deptData[0][0].toString();

        // 2. 获取该部门所有员工
        QString empSql = QString("SELECT e.emp_id, e.emp_name, e.position \
                               FROM employee e \
                               WHERE e.dept_id = %1")
                          .arg(deptId);
        QList<QString> empFields = {"emp_id", "emp_name", "position"};
        QList<QVariantList> employees;
        if (!m_dbOperator->selectDataBySql(empSql, empFields, employees) || employees.isEmpty())
        {
            throw QString("该部门没有员工");
        }

        // 3. 为每个员工计算工资并发放
        QString currentDate = QDate::currentDate().toString("yyyy-MM-dd");
        int successCount = 0;

        for (const auto &emp : employees)
        {
            QString empId = emp[0].toString();
            QString empName = emp[1].toString();
            QString position = emp[2].toString();

            // 3.1 计算基本工资
            double basicSalary = 7000.0; // 默认值
            if (position == "总经理")
                basicSalary = 20000.0;
            else if (position == "总监")
                basicSalary = 12000.0;
            else if (position == "工程师")
                basicSalary = 10000.0;

            // 3.2 计算扣除金额
            double deduction = 0.0;
            QString evalSql = QString("SELECT late_count, leave_count \
                                      FROM evaluation \
                                      WHERE emp_id = '%1' \
                                      AND eval_period = '%2'")
                              .arg(empId)
                              .arg(paymentPeriod);
            QList<QString> evalFields = {"late_count", "leave_count"};
            QList<QVariantList> evalData;
            if (m_dbOperator->selectDataBySql(evalSql, evalFields, evalData) && !evalData.isEmpty())
            {
                int lateCount = evalData[0][0].toInt();
                int leaveCount = evalData[0][1].toInt();

                // 计算迟到扣除
                deduction += lateCount * 100.0;

                // 计算请假扣除
                deduction += leaveCount * 100.0;

                // TODO: 需要获取早退和缺勤次数，当前数据库设计文档中没有明确说明这两个字段
                // 假设考核表中可能有相关字段，这里暂时不实现早退和缺勤的扣除
                // 实际应用中需要根据完整的数据库设计进行调整
            }
            else
            {
                // 没有找到考核记录，扣除金额为0
                deduction = 0.0;
            }

            // 3.3 计算实发工资
            double actualSalary = basicSalary - deduction;

            // 3.4 检查是否已存在该员工该周期的工资记录
            QHash<QString, QVariant> salaryConditions;
            salaryConditions.insert("emp_id", empId);
            salaryConditions.insert("payment_period", paymentPeriod);
            QList<QVariantList> salaryData;
            if (m_dbOperator->selectData("salary", {"salary_id"}, salaryConditions, salaryData) && !salaryData.isEmpty())
            {
                // 已存在工资记录，跳过
                qDebug() << QString("员工 %1 已存在 %2 周期的工资记录，跳过").arg(empName).arg(paymentPeriod);
                continue;
            }

            // 3.5 插入工资记录
            QList<QString> salaryFields = {"emp_id", "basic_salary", "deduction", "actual_salary", "payment_date", "payment_period"};
            QVariantList salaryValues;
            salaryValues << empId << basicSalary << deduction << actualSalary << currentDate << paymentPeriod;

            if (m_dbOperator->insertRowData("salary", salaryFields, salaryValues))
            {
                successCount++;
            }
            else
            {
                throw QString("插入员工 %1 工资记录失败: %2").arg(empName).arg(m_dbOperator->lastError());
            }
        }

        // 提交事务
        if (!m_dbOperator->commit())
        {
            throw QString("提交事务失败: " + m_dbOperator->lastError());
        }

        emit operationResult(true, QString("成功为 %1 部门 %2 名员工发放工资").arg(deptName).arg(successCount));
        return true;
    }
    catch (const QString &error)
    {
        m_dbOperator->rollback();
        emit operationResult(false, error);
        return false;
    }
}

// 同意请假申请
bool AdminManager::approveLeaveRequest(const QString &requestId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return false;
    }
    
    // 检查requestId是否为空
    if (requestId.isEmpty()) {
        emit operationResult(false, "申请ID不能为空");
        return false;
    }
    
    // 更新请假申请状态为同意
    QHash<QString, QVariant> updateValues;
    updateValues.insert("status", "同意");
    
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("request_id", requestId);
    whereConditions.insert("status", "未审核");
    
    bool success = m_dbOperator->updateData("leave_request", updateValues, whereConditions);
    
    if (!success) {
        emit operationResult(false, "更新请假申请失败: " + m_dbOperator->lastError());
        return false;
    }
    
    if (m_dbOperator->getAffectedRows() == 0) {
        emit operationResult(false, "未找到待审核的请假申请或该申请已被处理");
        return false;
    }
    
    emit operationResult(true, "请假申请已同意");
    return true;
}
// 不同意请假申请
bool AdminManager::rejectLeaveRequest(const QString &requestId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return false;
    }

    // 检查requestId是否为空
    if (requestId.isEmpty()) {
        emit operationResult(false, "申请ID不能为空");
        return false;
    }

    // 更新请假申请状态为不同意
    QHash<QString, QVariant> updateValues;
    updateValues.insert("status", "不同意");

    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("request_id", requestId);
    whereConditions.insert("status", "未审核");

    bool success = m_dbOperator->updateData("leave_request", updateValues, whereConditions);

    if (!success) {
        emit operationResult(false, "更新请假申请失败: " + m_dbOperator->lastError());
        return false;
    }

    if (m_dbOperator->getAffectedRows() == 0) {
        emit operationResult(false, "未找到待审核的请假申请或该申请已被处理");
        return false;
    }

    emit operationResult(true, "请假申请已拒绝");
    return true;
}
QString AdminManager::getEmpIdByRequestId1(const QString &requestId, SqlOperator *dbOperator) {
    // 1. 检查数据库是否打开
    if (!dbOperator->isOpen()) {
        qWarning() << "数据库未打开";
        return "";
    }

    // 2. 配置查询参数：查询emp_id字段，条件是request_id匹配
    QString tableName = "transfer_request"; // 调岗申请表名
    QList<QString> fields = {"emp_id"};     // 要查询的字段（员工工号）
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("request_id", requestId); // 查询条件：request_id = 目标ID

    // 3. 执行查询
    QList<QVariantList> queryResult; // 存储查询结果
    bool success = dbOperator->selectData(tableName, fields, whereConditions, queryResult);

    // 4. 解析结果
    if (!success) {
        qWarning() << "查询失败：" << dbOperator->lastError();
        return "";
    }
    if (queryResult.isEmpty()) {
        qWarning() << "未找到request_id对应的记录：" << requestId;
        return "";
    }

    // 结果格式：queryResult是QList<QVariantList>，每个元素是一行数据
    // 此处只查了emp_id一个字段，所以取第一行第一列的值
    return queryResult.first().first().toString().trimmed();
}
// 处理流程：获取员工ID → 检查当月考核表是否存在 → 存在则更新leave_count+1
bool AdminManager::processEvaluationLeaveCount(const QString &requestId)
{
    // 1. 先通过request_id获取员工ID（复用之前的逻辑）
    QString empId = getEmpIdByRequestId1(requestId, m_dbOperator);


    // 2. 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return false;
    }

    // 3. 构造当月周期条件（格式需与考核表中的eval_period一致，如"2023-08"）
    QString currentMonth = QDate::currentDate().toString("yyyy-MM");

    // 4. 检查该员工当月的考核表是否存在
    QList<QString> checkFields = {"emp_id"}; // 仅需查询存在性，查一个字段即可
    QHash<QString, QVariant> checkConditions;
    checkConditions.insert("emp_id", empId);       // 员工ID条件
    checkConditions.insert("eval_period", currentMonth); // 当月周期条件

    QList<QVariantList> evalResult;
    bool checkSuccess = m_dbOperator->selectData(
        "evaluation",        // 考核表表名
        checkFields,         // 要查询的字段
        checkConditions,     // 查询条件
        evalResult           // 存储查询结果
    );

    if (!checkSuccess) {
        emit operationResult(false, "查询考核表失败: " + m_dbOperator->lastError());
        return false;
    }

    // 5. 若当月考核记录存在，则更新leave_count+1
    if (!evalResult.isEmpty()) {
        // 构造更新数据：leave_count = leave_count + 1
        QHash<QString, QVariant> updateData;
        // 注意：需确保数据库支持字段自增表达式（此处直接传递SQL表达式）
        updateData.insert("leave_count", "leave_count + 1");

        // 执行更新（条件与查询时一致：员工ID + 当月周期）
        bool updateSuccess = m_dbOperator->updateData(
            "evaluation",
            updateData,
            checkConditions // 复用查询时的条件（emp_id + 当月）
        );

        if (updateSuccess) {
            emit operationResult(true, QString("员工%1当月考核表请假次数已更新").arg(empId));
            return true;
        } else {
            emit operationResult(false, "更新请假次数失败: " + m_dbOperator->lastError());
            return false;
        }
    } else {
        // 当月考核表不存在的处理
        emit operationResult(true, QString("员工%1当月暂无考核记录，无需更新").arg(empId));
        return true;
    }
}
// 发放全体员工工资
bool AdminManager::distributeAllSalaries(const QString &paymentPeriod)
{
    // 验证输入
    if (paymentPeriod.isEmpty())
    {
        emit operationResult(false, "发放周期不能为空");
        return false;
    }

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        emit operationResult(false, "数据库连接失败");
        return false;
    }

    // 开始事务
    if (!m_dbOperator->transaction())
    {
        emit operationResult(false, "开启事务失败: " + m_dbOperator->lastError());
        return false;
    }

    try
    {
        // 1. 获取所有员工
        QString empSql = "SELECT e.emp_id, e.emp_name, e.position, d.dept_name \
                           FROM employee e \
                           JOIN department d ON e.dept_id = d.dept_id";
        QList<QString> empFields = {"emp_id", "emp_name", "position", "dept_name"};
        QList<QVariantList> employees;
        if (!m_dbOperator->selectDataBySql(empSql, empFields, employees) || employees.isEmpty())
        {
            throw QString("没有员工数据");
        }

        // 2. 为每个员工计算工资并发放
        QString currentDate = QDate::currentDate().toString("yyyy-MM-dd");
        int successCount = 0;

        for (const auto &emp : employees)
        {
            QString empId = emp[0].toString();
            QString empName = emp[1].toString();
            QString position = emp[2].toString();
            QString deptName = emp[3].toString();

            // 2.1 计算基本工资
            double basicSalary = 7000.0; // 默认值
            if (position == "总经理")
                basicSalary = 20000.0;
            else if (position == "总监")
                basicSalary = 12000.0;
            else if (position == "工程师")
                basicSalary = 10000.0;

            // 2.2 计算扣除金额
            double deduction = 0.0;
            QString evalSql = QString("SELECT late_count, leave_count \
                                      FROM evaluation \
                                      WHERE emp_id = '%1' \
                                      AND eval_period = '%2'")
                              .arg(empId)
                              .arg(paymentPeriod);
            QList<QString> evalFields = {"late_count", "leave_count"};
            QList<QVariantList> evalData;
            if (m_dbOperator->selectDataBySql(evalSql, evalFields, evalData) && !evalData.isEmpty())
            {
                int lateCount = evalData[0][0].toInt();
                int leaveCount = evalData[0][1].toInt();

                // 计算迟到扣除
                deduction += lateCount * 100.0;

                // 计算请假扣除
                deduction += leaveCount * 100.0;
            }
            else
            {
                // 没有找到考核记录，扣除金额为0
                deduction = 0.0;
            }

            // 2.3 计算实发工资
            double actualSalary = basicSalary - deduction;

            // 2.4 检查是否已存在该员工该周期的工资记录
            QHash<QString, QVariant> salaryConditions;
            salaryConditions.insert("emp_id", empId);
            salaryConditions.insert("payment_period", paymentPeriod);
            QList<QVariantList> salaryData;
            if (m_dbOperator->selectData("salary", {"salary_id"}, salaryConditions, salaryData) && !salaryData.isEmpty())
            {
                // 已存在工资记录，跳过
                qDebug() << QString("员工 %1 已存在 %2 周期的工资记录，跳过").arg(empName).arg(paymentPeriod);
                continue;
            }

            // 2.5 插入工资记录
            QList<QString> salaryFields = {"emp_id", "basic_salary", "deduction", "actual_salary", "payment_date", "payment_period"};
            QVariantList salaryValues;
            salaryValues << empId << basicSalary << deduction << actualSalary << currentDate << paymentPeriod;

            if (m_dbOperator->insertRowData("salary", salaryFields, salaryValues))
            {
                successCount++;
            }
            else
            {
                throw QString("插入员工 %1 工资记录失败: %2").arg(empName).arg(m_dbOperator->lastError());
            }
        }

        // 提交事务
        if (!m_dbOperator->commit())
        {
            throw QString("提交事务失败: " + m_dbOperator->lastError());
        }

        emit operationResult(true, QString("成功为 %1 名员工发放工资").arg(successCount));
        return true;
    }
    catch (const QString &error)
    {
        m_dbOperator->rollback();
        emit operationResult(false, error);
        return false;
    }
}
// 查看全体员工月考核信息
QList<QVariantList> AdminManager::getAllEmployeesMonthlyAssessment(const QString &evalPeriod, int deptId)
{
    QList<QVariantList> results;

    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return results;
    }

    // 检查evaluation表是否存在
    if (!m_dbOperator->isExistTable("evaluation")) {
        emit operationResult(false, "evaluation表不存在");
        return results;
    }

    // 构建SQL查询语句
    QString sql;
    if (evalPeriod.isEmpty() && deptId == -1) {
        sql = "SELECT e.emp_id, e.emp_name, d.dept_id, d.dept_name, ev.late_count, ev.leave_count, ev.early_leave_count, ev.late_and_leave_count, ev.absent_count, ev.score, ev.eval_period "
              "FROM evaluation ev "
              "INNER JOIN employee e ON ev.emp_id = e.emp_id "
              "INNER JOIN department d ON e.dept_id = d.dept_id "
              "ORDER BY ev.eval_period DESC, d.dept_id, e.emp_id";
    } else if (evalPeriod.isEmpty()) {
        sql = QString("SELECT e.emp_id, e.emp_name, d.dept_id, d.dept_name, ev.late_count, ev.leave_count, ev.early_leave_count, ev.late_and_leave_count, ev.absent_count, ev.score, ev.eval_period "
                      "FROM evaluation ev "
                      "INNER JOIN employee e ON ev.emp_id = e.emp_id "
                      "INNER JOIN department d ON e.dept_id = d.dept_id "
                      "WHERE d.dept_id = %1 "
                      "ORDER BY ev.eval_period DESC, e.emp_id").arg(deptId);
    } else if (deptId == -1) {
        sql = QString("SELECT e.emp_id, e.emp_name, d.dept_id, d.dept_name, ev.late_count, ev.leave_count, ev.early_leave_count, ev.late_and_leave_count, ev.absent_count, ev.score, ev.eval_period "
                      "FROM evaluation ev "
                      "INNER JOIN employee e ON ev.emp_id = e.emp_id "
                      "INNER JOIN department d ON e.dept_id = d.dept_id "
                      "WHERE ev.eval_period = '%1' "
                      "ORDER BY d.dept_id, e.emp_id").arg(evalPeriod);
    } else {
        sql = QString("SELECT e.emp_id, e.emp_name, d.dept_id, d.dept_name, ev.late_count, ev.leave_count, ev.early_leave_count, ev.late_and_leave_count, ev.absent_count, ev.score, ev.eval_period "
                      "FROM evaluation ev "
                      "INNER JOIN employee e ON ev.emp_id = e.emp_id "
                      "INNER JOIN department d ON e.dept_id = d.dept_id "
                      "WHERE ev.eval_period = '%1' AND d.dept_id = %2 "
                      "ORDER BY e.emp_id").arg(evalPeriod).arg(deptId);
    }

    // 定义要查询的字段
    QList<QString> fields;
    fields << "emp_id" << "emp_name" << "dept_id" << "dept_name" << "late_count" << "leave_count" << "early_leave_count" << "late_and_leave_count" << "absent_count" << "score" << "eval_period";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success) {
        emit operationResult(false, QString("查询员工考核信息失败: %1").arg(m_dbOperator->lastError()));
    } else {
        emit operationResult(true, QString("成功查询到 %1 条员工考核记录").arg(results.size()));
    }

    return results;
}
QList<QVariantList> AdminManager::getAllDepartments()
{
    QList<QVariantList> results;

    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return results;
    }

    // 检查department表是否存在
    if (!m_dbOperator->isExistTable("department")) {
        emit operationResult(false, "department表不存在");
        return results;
    }

    // 构建SQL查询语句
    QString sql = "SELECT d.dept_id, d.dept_name, d.dept_head_id, e.emp_name, "
                     "(SELECT COUNT(*) FROM employee WHERE dept_id = d.dept_id) AS dept_count "
                     "FROM department d LEFT JOIN employee e ON d.dept_head_id = e.emp_id "
                     "ORDER BY d.dept_id";
    // 定义要查询的字段
    QList<QString> fields;
    fields << "dept_id" << "dept_name" << "dept_head_id" << "emp_name"<<"dept_count";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success) {
        emit operationResult(false, QString("查询部门信息失败: %1").arg(m_dbOperator->lastError()));
    }

    return results;
}
// 查看特定部门的人员信息
QList<QVariantList> AdminManager::getDepartmentEmployees(int deptId)
{
    QList<QVariantList> results;

    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return results;
    }

    // 检查employee表是否存在
    if (!m_dbOperator->isExistTable("employee")) {
        emit operationResult(false, "employee表不存在");
        return results;
    }

    // 构建SQL查询语句
    QString sql = QString("SELECT emp_id, emp_name, gender, position FROM employee WHERE dept_id = %1 ORDER BY emp_id").arg(deptId);

    // 定义要查询的字段
    QList<QString> fields;
    fields << "emp_id" << "emp_name" << "gender" << "position";

    // 执行查询
    bool success = m_dbOperator->selectDataBySql(sql, fields, results);

    if (!success) {
        emit operationResult(false, QString("查询部门员工信息失败: %1").arg(m_dbOperator->lastError()));
    }

    return results;
}
// 添加新部门
bool AdminManager::addDepartment(const QString &deptName, const QString &managerId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return false;
    }

    // 验证输入
    if (deptName.isEmpty()) {
        emit operationResult(false, "部门名称不能为空");
        return false;
    }

    // 检查部门名称是否已存在
    QList<QString> fields = {"dept_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("dept_name", deptName);
    QList<QVariantList> data;
    if (m_dbOperator->selectData("department", fields, whereConditions, data)) {
        if (!data.isEmpty()) {
            emit operationResult(false, "部门名称已存在");
            return false;
        }
    } else {
        emit operationResult(false, "检查部门名称失败: " + m_dbOperator->lastError());
        return false;
    }

    // 检查经理ID是否存在（如果提供）
    if (!managerId.isEmpty()) {
        fields.clear();
        fields << "emp_id";
        whereConditions.clear();
        whereConditions.insert("emp_id", managerId);
        data.clear();
        if (m_dbOperator->selectData("employee", fields, whereConditions, data)) {
            if (data.isEmpty()) {
                emit operationResult(false, "指定的经理ID不存在");
                return false;
            }
        } else {
            emit operationResult(false, "检查经理ID失败: " + m_dbOperator->lastError());
            return false;
        }
    }

    // 插入新部门
    QList<QString> deptFields = {"dept_name", "dept_head_id", "dept_count"};
    QVariantList deptData;
    deptData << deptName << managerId << 0;

    if (!m_dbOperator->insertRowData("department", deptFields, deptData)) {
        emit operationResult(false, "添加部门失败: " + m_dbOperator->lastError());
        return false;
    }

    emit operationResult(true, "部门添加成功");
    return true;
}
// 删除部门
bool AdminManager::deleteDepartment(int deptId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen()) {
        emit operationResult(false, "数据库连接未打开");
        return false;
    }

    // 检查部门是否存在
    QList<QString> fields = {"dept_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("dept_id", deptId);
    QList<QVariantList> data;
    if (m_dbOperator->selectData("department", fields, whereConditions, data)) {
        if (data.isEmpty()) {
            emit operationResult(false, "部门不存在");
            return false;
        }
    } else {
        emit operationResult(false, "检查部门失败: " + m_dbOperator->lastError());
        return false;
    }

    // 检查部门是否有员工
    fields.clear();
    fields << "emp_id";
    whereConditions.clear();
    whereConditions.insert("dept_id", deptId);
    data.clear();
    if (m_dbOperator->selectData("employee", fields, whereConditions, data)) {
        if (!data.isEmpty()) {
            emit operationResult(false, "部门中仍有员工，无法删除");
            return false;
        }
    } else {
        emit operationResult(false, "检查部门员工失败: " + m_dbOperator->lastError());
        return false;
    }

    // 删除部门
    whereConditions.clear();
    whereConditions.insert("dept_id", deptId);
    if (!m_dbOperator->deleteData("department", whereConditions)) {
        emit operationResult(false, "删除部门失败: " + m_dbOperator->lastError());
        return false;
    }

    emit operationResult(true, "部门删除成功");
    return true;
}





